<?php

namespace app\admin\controller;


use app\admin\model\Admin;
use app\admin\model\AdminGroup;
use app\admin\model\Menu;
use app\admin\model\Substation;

/**
 * Author Yang You
 * Time:2018-10-18 16:34:13
 * Describe:员工管理
 * Class Admins
 * @package app\admin\controller
 */
class Admins extends Base
{

    //管理员列表
    public function index(){
        if(input("?table")) {
            $keyword = input("keyword/s");
            $Admin = new Admin();
            $result["code"] = 0;
            $result['data'] = $Admin->adminList($keyword);
            $result['count'] = $Admin->adminListCount($keyword);
        }
        return !empty($result) ? json($result) : view('index',[
            'title'         =>  '管理员列表',
        ]);
    }

    //添加修改管理员
    public function add(){
        $admin_id = input("admin_id/d",0);
        $Admin = new Admin();
        $AdminGroup = new AdminGroup();
        if(request()->isPost()){
            $data = input("post.");
            $check =  [//验证规则
                ["admin_name", "require", "登录名不能为空"],
                ["nick_name", "require", "昵称不能为空"],
                ["tel", "regex:/^1[0-9]{1}\d{9}$/", "手机号码输入有误"],
                ["group_id", "require", "请选择属于的角色"],
            ];
            //修改了或者添加了密码时候需要判断密码
            if(!empty($data["password"]) || empty($admin_id)){
                $check[] = ["password", "require|min:6|regex:/^(?![0-9]+$)(?![a-zA-Z]+$)/","密码不能为空|密码长度最小6位|密码必须是数字和字母组合"];
            }
            //没有设置或者没有修改密码
            if(empty($data["password"])){
                unset($data["password"]);
            }
            $msg = $Admin->checkData($data,$check);
            if ($msg === true) {
                if($Admin->checkFieldOnly("admin_name",$data["admin_name"],"admin_id",$admin_id)){
                    $result["code"] = 1;
                    $result["msg"] = '登录名已存在';
                }else{
                    if($Admin->checkFieldOnly("tel",$data["tel"],"admin_id",$admin_id)){
                        $result["code"] = 1;
                        $result["msg"] = '手机号码已存在';
                    }else{
                        if($Admin->checkSave($data["group_id"],$admin_id)) {
                            //获取角色名称
                            $data["group_name"] = $AdminGroup->getFieldValue("group_id", $data["group_id"], "group_name");
                            $data["is_frozen"] = !empty($data["is_frozen"]) ? $data["is_frozen"] : 0;//取消冻结设置
                            if ($Admin->mySave($data, "admin_id", $admin_id)) {
                                $result["code"] = 0;
                                $result["msg"] = "操作成功！";
                            } else {
                                $result["code"] = 10000;
                                $result["msg"] = "操作失败！";
                            }
                        }else{
                            $result["code"] = 20000;
                            $result["msg"] = "没有权限修改!";
                        }
                    }
                }
            }else {
                $result["code"] = 1;
                $result["msg"] = $msg;
            }
        }else {
            if (!empty($admin_id)) {
                //修改获取详情
                $dataInfo = $Admin->dataInfo("admin_id",$admin_id);
                $this->assign('dataInfo', $dataInfo);
            }
            $groupList = $AdminGroup->groupList();
            $groupPid = $this->admin["group_id"] == config("SuperAdminGroupId") ? 0 : $this->admin["group_id"];//设置pid
            $groupList = Menus::arrayToTree(collection($groupList)->toArray(),$groupPid,0,"group_id");
            $this->assign('groupList', $groupList);
        }
        return !empty($result) ? json($result): view('add',[
            'title'         =>  '添加修改管理员',
        ]);

    }

    //删除管理员
    public function del(){
        $admin_id = input("admin_id/d",0);
        $Admin = new Admin();
        if(!empty($admin_id)){
            $group_id = $Admin->getFieldValue("admin_id", $admin_id, "group_id");
            if($Admin->checkSave($group_id,$admin_id)) {
                if ($Admin->del("admin_id", $admin_id, true)) {
                    $result["code"] = 0;
                    $result["msg"] = "操作成功!";
                } else {
                    $result["code"] = 10000;
                    $result["msg"] = "操作失败！";
                }
            }else{
                $result["code"] = 20000;
                $result["msg"] = "没有权限删除!";
            }
        }else{
            $result["code"] = 1;
            $result["msg"] = "admin_id参数为空!";
        }
        return json($result);
    }

    //修改管理员信息
    public function editAdmin(){
        $admin_id = input("admin_id/d",0);
        $Admin = new Admin();
        if(!empty($admin_id)){
            $data = input("post.");
            $check = [];//验证规则
            //修改冻结状态
            if(!empty($data["is_frozen"])){
                $check[] = ["is_frozen", "in:0,1", "冻结修改错误"];
            }
            //修改密码
            if(!empty($data["password"])){
                $check[] = ["password", "require|min:6|regex:/^(?![0-9]+$)(?![a-zA-Z]+$)/","密码不能为空|密码长度最小6位|密码必须是数字和字母组合"];
            }
            $msg = $Admin->checkData($data,$check);
            if($msg === true) {
                if ($Admin->mySave($data, "admin_id", $admin_id)) {
                    $result["code"] = 0;
                    $result["msg"] = "操作成功!";
                } else {
                    $result["code"] = 10000;
                    $result["msg"] = "操作失败！";
                }
            }else{
                $result["code"] = 1;
                $result["msg"] = $msg === false ? '修改信息错误' : $msg;
            }
        }else{
            $result["code"] = 1;
            $result["msg"] = "admin_id参数为空!";
        }
        return json($result);
    }


    //角色列表
    public function adminGroup(){
        $keyword = input('keyword/s');//搜索关键字
        if(input("?table")) {
            $AdminGroup = new AdminGroup();
            $result["code"] = 0;
            $result["data"] = $AdminGroup->groupList($keyword);
            if(empty($keyword)) {//搜索不保持树结构
                $groupPid = $this->admin["group_id"] == config("SuperAdminGroupId") ? 0 : $this->admin["group_id"];//设置pid
                $result["data"] = Menus::arrayToTree(collection($result["data"])->toArray(),$groupPid,0,"group_id");
            }
            return json($result);
        }
        return view('adminGroup',[
            'title'     =>  '角色列表',
        ]);
    }

    //添加修改角色
    public function addGroup(){
        $group_id = input('group_id/d',0);
        $AdminGroup = new AdminGroup();
        if(request()->isPost()){
            $data = input("post.");
            $msg = $AdminGroup->checkData($data, [
                ["group_name", "require", "角色名称不能为空"]
            ]);
            if ($msg === true) {
                if($AdminGroup->checkFieldOnly("group_name",$data["group_name"],"group_id",$group_id)){
                    $result["code"] = 1;
                    $result["msg"] = '角色名称已存在';
                }else {
                    $data["parent_id"] = !empty($data["parent_id"]) ? $data["parent_id"] : $this->admin["group_id"];//设置pid
                    if($AdminGroup->checkSave($group_id,$data["parent_id"])) {
                        if ($AdminGroup->mySave($data, 'group_id', $group_id)) {
                            if (!empty($group_id)) {
                                //修改管理员表
                                $Admin = new Admin();
                                $Admin->setFieldValue("group_id", $group_id, "group_name", $data["group_name"]);
                            }
                            $result["code"] = 0;
                            $result["msg"] = "操作成功!";
                            $AdminGroup->cacheSave($data["parent_id"]);//更新缓存
                        } else {
                            $result["code"] = 10000;
                            $result["msg"] = "操作失败!";
                        }
                    }else{
                        $result["code"] = 20000;
                        $result["msg"] = "没有权限修改!";
                    }
                }
            }else {
                $result["code"] = 1;
                $result["msg"] = $msg;
            }
            return json($result);
        }
        if(!empty($group_id)){
            //修改获取详情
            $dataInfo = $AdminGroup->dataInfo("group_id",$group_id);
            $this->assign('dataInfo',$dataInfo);
        }
        $groupList = $AdminGroup->groupList();
        $groupPid = $this->admin["group_id"] == config("SuperAdminGroupId") ? 0 : $this->admin["group_id"];//设置pid
        $groupList = Menus::arrayToTree(collection($groupList)->toArray(),$groupPid,0,"group_id");
        return view('addGroup',[
            'title'     =>  '添加修改角色',
            'groupList' =>  $groupList,
        ]);
    }

    //删除角色
    public function delGroup(){
        $group_id = input('group_id/d',0);
        if(!empty($group_id) && $group_id != config("SuperAdminGroupId")){
            if($group_id == config("SuperAdminGroupId")){//验证是不是超级管理员角色
                $result['msg'] = '超级管理员角色不能删除！';
            }else{
                $AdminGroup = new AdminGroup();
                $parent_id = $AdminGroup->getFieldValue("group_id", $group_id, "parent_id");
                if($AdminGroup->checkSave($group_id,$parent_id)) {
                    $groupNumber = $AdminGroup->getFieldCount("parent_id",$group_id);
                    if(!$groupNumber) {//验证子角色
                        $Admin = new Admin();
                        $adminNumber = $Admin->getFieldCount("group_id",$group_id);
                        if(!$adminNumber) {//验证管理员
                            if ($AdminGroup->del("group_id", $group_id, true)) {
                                $result["code"] = 0;
                                $result["msg"] = "操作成功!";
                            } else {
                                $result["code"] = 10000;
                                $result["msg"] = "操作失败!";
                            }
                        }else{
                            $result["code"] = 1;
                            $result["msg"] = "操作失败，该角色下有（".$adminNumber."）个管理员！";
                        }
                    }else{
                        $result["code"] = 1;
                        $result["msg"] = "操作失败，该角色下有（".$groupNumber."）个子角色！";
                    }
                }else{
                    $result["code"] = 20000;
                    $result["msg"] = "没有权限删除!";
                }
            }
        }else{
            $result['msg'] = 'group_id,参数错误';
        }
        return json($result);
    }

    //设置角色权限
    public function setGroup(){
        $group_id = input('group_id/d');
        if(!empty($group_id)) {
            if ($group_id == config("SuperAdminGroupId")) {//验证是不是超级管理员角色
                $result['msg'] = '超级管理员角色不能设置权限，默认拥有全部权限！';
            } else {
                $Menu = new Menu();
                $AdminGroup = new AdminGroup();
                if(request()->isPost()) {
                    $menusStr = '';
                    $menus = input('menus/a');
                    //设置角色权限
                    if($Menu->checkSetMenuList($group_id,$menus)) {
                        if(!empty($menus)) {//不为空就循环取值
                            $menusStr = ArrayToStr($menus);
                        }
                        if ($AdminGroup->setFieldValue("group_id", $group_id, "menus", $menusStr)) {
                            $result["code"] = 0;
                            $result["msg"] = "操作成功!";
                        } else {
                            $result["code"] = 10000;
                            $result["msg"] = "操作失败！";
                        }
                    }else{
                        $result["code"] = 20000;
                        $result["msg"] = "有超出权限的菜单设置!";
                    }
                }else{
                    //获取菜单
                    $menuAllList = $Menu->setMenuList($group_id);
                    $menuAllList =  generateTree(collection($menuAllList)->toArray());//获取树结构菜单下拉使用
                    $this->assign('menuAllList', $menuAllList);
                    //获取自己角色权限
                    $menus = $AdminGroup->getFieldValue("group_id", $group_id, "menus");
                    $this->assign('menus', $menus);
                }
            }
        }else{
            $result["code"] = 1;
            $result['msg'] = 'group_id,参数错误';
        }
        return !empty($result) ? json($result) : view('setGroup',[
            'title'         =>  '角色权限设置',
            'group_id'      =>  $group_id,
        ]);
    }

    //设置网站权限
    public function setSubstationGroup(){
        $group_id = input('group_id/d');
        if(!empty($group_id) && $group_id != config("SuperAdminGroupId")) {
            $AdminGroup = new AdminGroup();
            $Substation = new Substation();
            if(request()->isPost()) {
                $str = '';
                $substations = input('substations/a');
                if($Substation->checkSetUserList($group_id,$substations)) {
                    if (!empty($substations)) {//不为空就循环取值
                        $str = ArrayToStr($substations);
                    }
                    //设置角色权限
                    if ($AdminGroup->setFieldValue("group_id", $group_id, "substations", $str)) {
                        $result["code"] = 0;
                        $result["msg"] = "操作成功!";
                    } else {
                        $result["code"] = 10000;
                        $result["msg"] = "操作失败！";
                    }
                }else{
                    $result["code"] = 20000;
                    $result["msg"] = "有超出权限的网站设置!";
                }
            }else{
                //获取网站
                $userList = $Substation->setUserList($group_id);
                $this->assign('userList', $userList);
                //获取自己角色权限
                $substations = $AdminGroup->getFieldValue("group_id", $group_id, "substations");
                $this->assign('substations', $substations);
            }
        }else{
            $result["code"] = 1;
            $result['msg'] = 'group_id,参数错误';
        }
        return !empty($result) ? json($result) : view('setSubstationGroup',[
            'title'         =>  '设置网站权限',
            'group_id'      =>  $group_id,
        ]);
    }
}
